# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time      :2022/8/3 0003 0:28
# @Author    :jiaxuesong


'''
导包

定义发送邮件类
    定义初始化函数，配置邮箱属性
        发件人
        收件人
        邮件主题
        服务
        用户名
        密码

    定义外围发送邮件调用方法

'''

# 导包
import smtplib
import os
import time
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from appium_test.common.log import logger
from appium_test.common.readConfig import ReadConfig


#定义发送邮件类
class SendEmail(object):
    #定义初始化函数
    def __init__(self):
        #实例化读取配置文件方法
        rea = ReadConfig()
        self.sender = rea.get_config('EMAIL', 'sender')
        self.receiver = rea.get_config('EMAIL', 'receiver')
        t = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime())
        self.title = 'App自动化测试报告' + t
        self.smtpserver = rea.get_config('EMAIL', 'smtp_server')
        self.username = rea.get_config('EMAIL', 'username')
        self.password = rea.get_config('EMAIL', 'password')


    def send_config(self, file):
        #获取测试报告目录
        #获取目录下所有html内容


        with open(file, 'rb') as f:
            mail_body = f.read()
            # 组装邮件内容和标题
            self.msg = MIMEMultipart()
            # 添加附件内容
            att = MIMEText(mail_body, 'plain', 'UTF-8')
            att['Content-Type'] = 'application/octet-stream'
            att['Content-Disposition'] = 'attachment; filename=report.html'
            self.msg.attach(att)
            # 添加文件的文本内容
            content = 'app自动化测试报告'
            self.msg.attach(MIMEText(content, 'plain', 'UTF-8'))
            self.msg['Subject'] = Header(self.title, 'UTF-8')
            self.msg['From'] = self.sender
            self.msg['To'] = '.'.join(self.receiver)


        #登录并发送邮件
    def send_email(self, file):
        self.send_config(file)
        try:
            #实例化smtp类
            smtp = smtplib.SMTP()
            # 使用smtp链接服务器
            smtp.connect(self.smtpserver)
            # 登录邮箱
            smtp.login(self.username, self.password)
            # 配置邮箱发送属性
            smtp.sendmail(self.sender, self.receiver, self.msg.as_string())
        except Exception as msg:
            logger.info(f'邮件发送失败，失败原因：{msg}')
        else:
            logger.info('邮件发送成功')
        finally:
            smtp.quit()


if __name__ == '__main__':
    re = SendEmail()
    re.send_email(os.path.dirname(os.path.dirname(__file__)) + r'/testReport/2022_08_03_01_10_25_report.html')
